package com.mansoor.app.islamicnames.dao;

import com.mansoor.app.islamicnames.beans.Name;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: TKMAQ61
 * Date: Oct 16, 2009
 * Time: 8:54:44 AM
 */
public class InMemoryDB
{
    private List<Name> names;
    private String filename;
    private Map<String, Name> nameMap = new HashMap<String, Name>();


    private synchronized void LoadDB() throws DocumentException
    {
        if (names == null)
        {
            SAXReader reader = new SAXReader();
            final Document document = reader.read(this.getClass().getResourceAsStream(filename));
            List<Name> nameList = new ArrayList<Name>();
            final org.dom4j.Element root = document.getRootElement();

            // iterate through child elements of root
            for (Iterator i = root.elementIterator(); i.hasNext();)
            {
                Element element = (Element) i.next();
                //  Iterator iterator = element.
                final Iterator iterator = element.elementIterator();

                Name name = new Name();
                while (iterator.hasNext())
                {
                    Element o = (Element) iterator.next();
                    String elemantName = o.getName();

                    if (elemantName.equals("id"))
                    {
                        name.setId(Integer.parseInt(o.getTextTrim()));

                    }
                    else if (elemantName.equals("name"))
                    {
                        name.setName(o.getTextTrim());

                    }
                    else if (elemantName.equals("gender"))
                    {
                        name.setGender(o.getTextTrim());
                    }
                    else if (elemantName.equals("meaning"))
                    {
                        name.setMeaning(o.getTextTrim());
                    }

                }

                nameMap.put(name.getName(), name);
                nameList.add(name);
            }
            this.names = nameList;
        }

    }

    public List<Name> getNames()
    {
        return names;
    }

    public void setFilename(String filename)
    {
        this.filename = filename;
    }

    public Map<String, Name> getNameMap()
    {
        return nameMap;
    }
}
